<?php
declare (strict_types = 1);

namespace app\common\controller;

use think\Request;
use wechat\Wechat;

class Api extends App
{
    protected $model;
    protected $where = [];
    protected $limit = 20;
    protected $order;
    protected $select = false;
    protected $field;
    //需要关联的表单,模型中的方法
    protected $with = [];
    //微信账户参数
    protected $appid = 'wx2689638cda0e034e';
    protected $appsecret = '68c6adee63df501f159915774a83bb74';
    //商户号
    protected $mchid = '';
    //APP秘钥
    protected $mchkey = '';  //等待更换新秘钥
    //是否需要控制器下全方法登录验证
    protected $check = false;
    //需要单独登录验证的方法
    protected $action = [];
    //登录用户数据
    protected $userinfo = [];
    //登录商户数据
    protected $businessinfo = [];
    protected $business_check = false;
    //商户端的
    protected $sh_easy_config = [
        'app_id'=>'wx1f8b29049a83e814',
        'secret' => 'cc7f15fa777c2c3b6e8de5e579f579b2',
    ];
    //用户端的
    protected $yh_easy_config = [
        'app_id' => 'wx2689638cda0e034e',
        'secret' => '68c6adee63df501f159915774a83bb74',
    ];
    public function initialize()
    {
        $this->model = app('app\api\model\\' . request()->controller());
        //用户端验证，微信授权登录
        if ($this->check || in_array(request()->action(), $this->action)) {
            $this->checkLogin();
        }
        //门店端验证，账号密码登录
        if($this->business_check){
            $this->businessCheckLogin();
        }
        parent::initialize(); // TODO: Change the autogenerated stub
    }
    //用户端验证
    protected function checkLogin($check = true)
    {
        //判断用户令牌是否存在
        $token = request()->header('Access-Token', '');
        if (empty($token)) {
            $return = msgerror("通讯令牌错误", ['token' => random(32)]);
            die($return->getContent());
        } else {
            //微信登录code
            $wxcode = request()->param('wxcode', '');
            if (!empty($wxcode)) {
                //通过微信授权取得微信openid;
                $wechat = Wechat::instance($this->appid, $this->appsecret);
                $miniprogram = $wechat->miniprogram();
                if ($miniprogram->code2session($wxcode)) {
                    $user = app('app\api\model\UserIndex')->usercheck($miniprogram->openid, $token);
                    if (empty($user)) {
                        $return = msgerror("用户信息入库失败");
                        die($return->getContent());
                    } else {
                        $this->userinfo = urladd($user->toArray());
                    }
                } else {
                    $return = msgerror("微信接口调用失败:" . $miniprogram->getErrMsg());
                    die($return->getContent());
                }
            } else {
                $user = app('app\api\model\UserIndex')->where('access_token', '=', $token)->find();
                if (empty($user)) {
                    $return = msgerror("未登录，系统正在重新登录");
                    die($return->getContent());
                } else {
                    $this->userinfo = $user->toArray();
                }
            }
        }
    }
    //商户端验证
    public function businessCheckLogin()
    {
        //判断用户令牌是否存在
        $token = request()->header('Access-Token', '');
        if (empty($token)) {
            $return = msgerror("通讯令牌错误", ['token' => random(32)]);
            die($return->getContent());
        } else {
            $business = app('app\api\model\Business')->where('token', '=', $token)->find();
            if (empty($business)) {
                $return = msgerror("未登录，系统正在重新登录");
                die($return->getContent());
            } else {
                $this->businessinfo = $business->toArray();
            }
        }
    }
    //列表接口
    public function index()
    {
        if (input('post.limit')) {
            $this->limit = input('post.limit');
            if($this->limit>=9999){
                $this->select = true;
            }
        }
        $post = array_filter(input('post.'));
        if(isset($post['where']) && is_array($post['where'])){
            foreach ($post['where'] as $k=>$v){
                if($k == 'name'){
                    $this->where[] = [$k,'like','%'.$v.'%'];
                }elseif($k == 'user_index_id'){
                    if(!isset($this->userinfo) || empty($this->userinfo)){
                        $this->checkLogin();
                    }
                    $this->where[] = [$k,'=',$this->userinfo['id']];
                }else{
                    $this->where[] = [$k,'=',$v];
                }
            }
        }
        $order = $post['order'] ?? [];
        if (!empty($order)) {
            if (is_string($order)) {
                if (strstr($order, ',')) {
                    $order = explode(',', $order);
                    $arr = [];
                    foreach ($order as $k => $v) {
                        $arr[$v] = 'desc';
                    }
                    $order = $arr;
                }
            }
        } elseif(!empty($this->order)){
            $order = $this->order;
        } else {
            $order = 'id desc';
        }
        if ($this->select) {
            $list = $this->model->with($this->with)->order($order)->where($this->where)->select();
        } else {
            if(input('find')){
                $list = $this->model->with($this->with)->order($order)->where($this->where)->find();
            }else{

                $list = $this->model->with($this->with)->order($order)->where($this->where)->paginate($this->limit);
            }
        }
        if (!empty($list)) {
            $list = $list->toArray();
            $list = $this->index_handel($list);
            if(isset($this->with)){
                if(isset($list['total'])){
                    //多条数据三数组以上，有分页
                    foreach ($this->with as $v){
                        foreach ($list['data'] as $kk=>$vv){
                            urladd($list['data'][$kk][$v]);
                        }
                    }
                }elseif(isset($list[0])){
                    //多条数据二数组以上，无分页
                    foreach ($this->with as $v){
                        foreach ($list as $kk=>$vv){
                            urladd($list[$kk][$v]);
                        }
                    }
                }else{
                    //1条数据，一维数组
                    foreach ($this->with as $v){
                        urladd($list[$v]);
                    }
                }
            }
            urladd($list);
        }
        return datasuccess($list);
    }
    //数据添加
    public function add()
    {
        $post = array_filter(input('post.'));
        if(!empty($post)){
            $post = $this->add_handle($post);
            if(isset($post['status']) && $post['status'] == 'error'){
                return msgerror($post['msg'] ?? '参数缺失');
            }
            $this->model->save($post);
            return datasuccess();
        }else{
            return msgerror('参数缺失');
        }
    }
    //数据修改
    public function upload()
    {
        $post = array_filter(input('post.'));
        if(!empty($post)){
            if(!isset($post['id'])) return msgerror('缺少id');
            $post = $this->upload_handle($post);
            if(isset($post['status']) && $post['status'] == 'error'){
                return msgerror($post['msg'] ?? '参数缺失');
            }
            $a = $this->model::update($post);
            return datasuccess();
        }else{
            return msgerror('缺少参数');
        }
    }
    //详情接口
    public function view()
    {
        if (!input('post.id')) {
            return msgerror('缺少参数id');
        }
        $this->where[] = ['id', '=', input('post.id')];
        $list = $this->model->with($this->with)->where($this->where)->find()->toArray();

        urladd($list);
        $time = strtotime($list['update_time']);
        $list['update_time'] = date('Y-m-d',$time);
        if(!empty($this->with)){
            foreach ($this->with as $k=>$v) {
                if(is_string($v)){
                    urladd($list[$v]);
                }else{
                    urladd($list[$k]);
                }
            }
        }
        $list = $this->view_handel($list);
        return datasuccess($list);
    }

    //删除数据
    public function delete()
    {
        if (!input('post.id')) {
            return msgerror('缺少参数id');
        }
        if (strstr((string)input('post.id'), ',')) {
            $id = explode(',', input('post.id'));
        } else {
            $id = input('post.id');
        }
        $this->model::destroy($id);
        return datasuccess([], '删除成功');
    }

    //获取微信小程序后台AccessToken
    public function token()
    {
        if (!Cache::get('token') || (!Cache::get('time') || Cache::get('time') < time())) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->appsecret";
            $curl = curl_send(['url' => $url]);
            $token = json_decode($curl['content'])->access_token;
            Cache::set('token', $token);
            Cache::set('time', time() + 7200);
        } else {
            $token = Cache::get('token');
        }
        return $token;
    }

    //微信支付
    public function wx_pay($order)
    {
        if (!input('post.code')) return ['status'=>'error','msg'=>'缺少code'];
        $code = input('post.code');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$this->appid&secret=$this->appsecret&js_code=$code&grant_type=authorization_code";
        $curl = curl_send(['url' => $url]);
        if (strpos($curl['content'], 'errcode') || strpos($curl['content'], 'error')) return ['status'=>'error','msg'=>'获取openid失败:' . $curl['content']];
        $openid = explode(':', str_replace('}', '', str_replace('"', '', explode(',', $curl['content'])[1])))[1];
        $wechat = Wechat::instance($this->appid, $this->appsecret);
        $wepay = $wechat->pay($this->mchid, $this->mchkey);
        $params = [
            'body' => $order['name'],
            'detail' => $order['content'] ?? '没有介绍',
            'out_trade_no' => $order['order_no'],
            'total_fee' => $order['money'] * 100,
            'notify_url' => url('api/Order/notifyfwzx', [], '', true),
            'openid' => $openid
        ];
        $result = $wepay->unifiedorder($params);
        if($result){
            return ['status'=>'success','data'=>$result];
        }else{
            // return $wepay->getErrCode .':' .$wepay->getErrMsg();
            return ['status'=>'error','msg'=>'失败:' . $wepay->getErrCode . ':' . $wepay->getErrMsg()];
        }
    }
    //上传接口
    //图片上传
    public function image()
    {
        $param = $_FILES;
        if (!empty($param)) {
            $file = $param['file'];
            // pr($file);
            $param = upload_file($file, 1024*1024*15);
            if (!$param) {
                return msgerror($GLOBALS['upload_file_error']);
            }
            $param['file'] = $param['file'];
        }
        return datasuccess($param);
    }
    //添加前的数据单独处理方法
    public function add_handle($post)
    {
        return $post;
    }
    //修改前的数据单独处理方法
    public function upload_handle($post)
    {
        return $post;
    }
    //查询后的数据单独处理方法
    public function index_handel($list){
        return $list;
    }

    public function view_handel($list)
    {
        return $list;
    }
}
